import axios from 'axios'
import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

export default function List() {
    let navigate = useNavigate()
    let [ShowData, setShowData] = React.useState([])
    // 开始使用accessToken 来获取数据
    let refreshToken = async () => {
        const refreshToken = localStorage.getItem("RefreshToken")
        let { data, code, token } = (await axios.get("/refresh_token", {
            headers: { "Authorization": `Bearer ${refreshToken}` }
        })).data
        if (code === 401) {
            alert("登陆失败")
            // 返回登陆界面
            navigate("/home")
            return
        } else {
            // 设置新的段token
            localStorage.setItem("AccessToken", token.accessToken)
            // 重新获取数据
            getlist()
        }
    }
    // 将accessToken传给后端
    let getlist = async () => {
        let accessToken = localStorage.getItem("AccessToken")
        let {data,code} = (await axios.get("/list", {
            headers: { "Authorization": `Bearer ${accessToken}` }
        })).data
        if (code === 401) {
            refreshToken();
            return
        }
        setShowData(data)

    }
    useEffect(() => {
        getlist()
    },[])
    return (
        <div>
            <h1>列表页面</h1>
            <ul>
                {
                    ShowData.map((item,index)=>{
                        return <li key={index}>{item.name}</li>
                    })
                }
            </ul>
        </div>
    )
}
